<template>
    <div style="padding: 10px;">
        <!--<Particles></Particles>-->
        <!--功能区域-->
        <div style="margin: 10px 0">
            <el-button type="success" round @click="add">新增</el-button>
            <el-popconfirm
                    title="确定删除吗？"
                    @confirm="deleteBatch"
            >
                <template #reference>
                    <el-button type="danger" style="border-radius: 20px;margin-left: 10px">批量删除
                    </el-button>
                </template>

            </el-popconfirm>

        </div>

        <!--搜索-->
        <div style="margin: 10px; text-align: center;margin-left: -120px;border-radius: 20px">
            <el-input @keyup.enter.native="load" v-model="search" placeholder="请输入关键字"
                      style="border-radius: 20px;width: 20%;" clearable=""></el-input>
            <el-button type="primary" style="margin-left: 7px" @click="load">查询</el-button>
        </div>

        <el-table
                :data="tableData"
                border
                @selection-change="handleSelectionChange">
            stripe=""
            size="small"
            style="width: 100%">
            <el-table-column
                    type="selection"
                    width="55px"
            ></el-table-column>
            <el-table-column
                    prop="id"
                    sortable=""
                    label="ID">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="名称">
            </el-table-column>
            <el-table-column
                    prop="price"
                    label="价格/元">
            </el-table-column>
            <el-table-column
                    prop="author"
                    label="作者">
            </el-table-column>
            <el-table-column
                    prop="time"
                    label="出版时间">
            </el-table-column>
            <el-table-column
                    width="170px"
                    fixed="right"
                    label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="buy(scope.row.id)">购买</el-button>
                    <!--编辑-->
                    <el-button type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit" circle></el-button>

                    <!--删除-->
                    <el-button @click="handleDelete(scope.row.id)"
                               slot="reference" type="danger" icon="el-icon-delete" circle
                               style="margin-left: 10px"></el-button>


                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[5,10,20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>

            <!--新增-->
            <el-dialog

                    title="新增"
                    :visible.sync="dialogVisible"
                    width="30%">

                <el-form :model="form" label-width="120px">

                    <el-form-item label="书籍名称">
                        <el-input v-model="form.name" style="width: 80%"></el-input>
                    </el-form-item>
                    <el-form-item label="价格/元">
                        <el-input v-model="form.price" style="width: 80%"></el-input>
                    </el-form-item>
                    <el-form-item label="作者">
                        <el-input v-model="form.author" style="width: 80%"></el-input>
                    </el-form-item>

                    <el-form-item label="出版时间">
                        <el-date-picker v-model="form.time" value-format="yyyy-MM-dd hh:mm:ss" type="datetime"
                                        style="width: 80%" clearable=""></el-date-picker>
                    </el-form-item>


                </el-form>

                <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
            </el-dialog>
        </div>


    </div>
</template>

<script>


    import request from '../utils/request'
    import Particles from '../components/particles/index'

    export default {
        name: 'Book',
        components: {Particles},
        data() {
            return {
                users: {},
                form: {
                    userId: ''
                },
                user: {},
                ids:[],
                //新增
                dialogVisible: false,
                search: '',
                //当前页
                currentPage4: 1,
                pageSize: 5,
                total: 0,

                tableData: []
            }


        },
        created() {
            let userStr = sessionStorage.getItem("user") || "{}"
            this.users = JSON.parse(userStr)
            this.load()
            //请求服务端，确认当前登录用户的 合法信息
            // request.get("/user/" + this.user.id).then(res => {
            //     if (res.code === '0') {
            //         this.user = res.data
            //     }
            // })
        },
        methods: {
            buy(bookId) {
                request.get("/order/buy/" + bookId).then(res => {
                    // 请求成功跳转沙箱支付的页面
                    window.open(res.data)
                })
            },
            //查询
            load() {
                request.get('/book', {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        search: this.search
                    }

                }).then(res => {
                    console.log(res)
                    this.tableData = res.data.records
                    this.total = res.data.total


                })
            },

            //新增
            add() {


                this.dialogVisible = true
                this.form = {} //清空输入的表单
                this.load()


            },
            //保存到后台
            save() {
                if (this.form.id) {
//    更新
//                     if (this.form['newRole']) {
//                         this.form.role = parseInt(this.form['newRole'])
//                     }
                    request.put("/book", this.form).then(res => {
                        if (res.code == '0') {
                            this.$message({
                                message: '更新成功',
                                type: 'success',

                            });
                            this.load()
                        } else {
                            this.$message({

                                message: res.msg,
                                type: 'error',

                            })
                        }

                    })
                    this.dialogVisible = false
                    this.load()
                } else {
                    //    新增
                    this.form.userId = this.users.id
                    request.post("/book", this.form).then(res => {

                        console.log(res)
                        this.dialogVisible = false
                        if (res.code == '0') {


                            this.$message({
                                message: '添加成功',
                                type: 'success',

                            });
                            this.load()
                        }

                        else {
                            this.$message({

                                message: res.msg,
                                type: 'error',

                            })
                        }
                    })
                }


            },
            //编辑
            handleEdit(row) {
                // role:{
                //      id:1,
                //      displayName: '管理员'
                // }
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogVisible = true
                // this.roleName=(row.role===1 ?"管理员":"普通员工")
                // this.$nextTick(()=>{
                //     this.$refs['upload'].clearFiles() //清除历史文件列表
                // })
            },
            handleDelete(id) {

                this.$confirm('你确定要删除,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    request.delete("/book/" + id).then(res => {

                        this.$message({type: 'success', message: '删除成功!'})
                        this.load()
                    })
                }).catch(() => {
                    this.$message({type: 'success', message: '已取消删除'})
                })


            },

            handleSelectionChange(val){
                this.ids=val.map(v=>v.id)

            },
            //批量删除
            deleteBatch(){
                if (!this.ids.length) {
                    this.$message.warning("请选择数据！")
                    return
                }
                request.post("/book/deleteBatch",this.ids).then(res=>
                    {
                        if (res.code == '0'){
                            this.$message({
                                message: '批量删除成功',
                                type: 'success',

                            });
                            this.load()
                        } else {
                            this.$message({

                                message: res.msg,
                                type: 'error',

                            })
                        }
                    }
                )

            },




            //页码 每页的个数
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },
            //改变当前页
            handleCurrentChange(pageNum) {
                this.currentPage = pageNum
                this.load()
            },

        }
    }
</script>

<style scoped>

    el-input {
        border-radius: 20px
    }
</style>
